﻿#include"List.h"

/////
//创建节点：
LTNode* LTBuyNode(LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode==NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	newnode->_x = x;
	newnode->next = newnode->prev = newnode;
	return newnode;
}
LTNode* LTInit()
{
	LTNode* phead=LTBuyNode(-1);
	return phead;
}
void LTDestroy(LTNode** phead)
{
	LTNode* pcur = (*phead)->next;
	while (pcur != *phead)
	{
		LTNode* del = pcur->next;
		free(pcur);
		pcur = del;
	}
	//销毁头节点（哨兵位）：
	free(*phead);
	*phead = NULL;
	pcur = NULL;
}
void LTPrint(LTNode* phead)
{
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d",pcur->_x);
		pcur = pcur->next;
	}
	printf('\n');
}
bool LTEmpty(LTNode* phead)
{
	assert(phead);
	return phead->next == phead;
}

void LTPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* newnode = LTBuyNode(x);
	newnode->next = phead;
	newnode->prev = phead->prev;

	phead->prev->next = newnode;
	phead->prev = newnode;
}
void LTPopBack(LTNode* phead)
{
	assert(phead);
	LTNode* end = phead->next;
	LTNode* prev = end->prev;

	prev->next = phead;
	phead->prev = prev;
	free(end);
	end = NULL;
}
void LTPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* newnode = LTBuyNode(x);
	newnode->next = phead->next;
	newnode->prev = phead;

	phead->next->prev = newnode;
	phead->next = newnode;
}
void LTPopFront(LTNode* phead)
{
	assert(phead);
	LTNode* end = phead->next;//如果不存起来最后phead->next改变之后要删除的节点就再找不到了！
	end->next->prev = phead;
	phead->next = end->next;
	free(end);
	end = NULL;
}

//在pos位置之后插⼊数据
void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);
	LTNode* newnode = LTBuyNode(x);
	newnode->next = pos->next;
	newnode->prev = pos;

	pos->next->prev = newnode;
	pos->next = newnode;
}
void LTErase(LTNode* pos)//pos默认就给你存起来了不需要在创建一个新节点来记录
{
	assert(pos);
	pos->next->prev = pos->prev;
	pos->prev->next = pos->next;

	free(pos);
	pos = NULL;
}
LTNode* LTFind(LTNode* phead, LTDataType x)
{
	LTNode* pcur = phead->next;
	while (pcur!=phead)
	{
		if (pcur->_x=x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}